package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContextLoader {

    static String appBasePath;//webapps路径

    static String classPath = "/WEB-INF/classes";//.class文件在项目中的相对路径

    static String webxmlPath = "/WEB-INF/web.xml";//web.xml在项目中的相对路径

    static String htmlPath = "/";//静态文件在项目中的相对路径

    static Map<String, String> contextAbsoluteRootPath = new HashMap<>();

    //解析webapps路径
    //遍历webapp下的所有项目名称及绝对路径
    private static void initWebappPath(InputStream serverResource){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(serverResource);
            Element root = document.getRootElement();
            List<Element> hostList = root.selectNodes("//Host");
            appBasePath = hostList.get(0).attributeValue("appBase");
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        File root = new File(appBasePath);
        File[] files = root.listFiles();
        for (File file : files) {//遍历demo工程
            contextAbsoluteRootPath.put(file.getName(), file.getPath());
        }
    }

    //加载webapps下的servlet
    public static List<Context> initWebapps(InputStream serverResource) throws FileNotFoundException {
        initWebappPath(serverResource);

        List<Context> contexts = new ArrayList<>();
        for(Map.Entry<String, String> entry : contextAbsoluteRootPath.entrySet()){
            Context context = new Context();
            File webappResourceFile = new File(entry.getValue() + File.separator + webxmlPath);
            Map<String,HttpServlet> servletMap = ServletLoader.loadServlet(new FileInputStream(webappResourceFile), appBasePath + File.separator + entry.getKey() + File.separator + classPath);
            context.setName(entry.getKey());
            context.setAbsolutePath(entry.getValue());
            context.setClassPath(appBasePath + File.separator + entry.getKey() + classPath);
            context.setHtmlPath(appBasePath + File.separator + entry.getKey() + htmlPath);
            context.setServletMapping(servletMap);
            contexts.add(context);
        }

        return contexts;
    }

}
